const Router = require("koa-router")
const { Op } = require("sequelize")
const ResBody = require("../struct/ResBody")
const { Store, StoreHouse, User } = require("../model")
const router = new Router()
const utils = require("../utils/index.js")

// 门店列表
router.get("/index", async ctx => {
  console.log("ctx: %s==", ctx)
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return (ctx.body = new ResBody({
      success: false,
      code: 403,
      msg: "拒绝访问API"
    }))
  }
  const list = await Store.findAll({
    // order: [['sort', 'ASC']]
  })
  ctx.body = new ResBody({ data: { list } })
})
// 仓库列表
router.get("/house", async ctx => {
  console.log("ctx: %s==", ctx)
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return (ctx.body = new ResBody({
      success: false,
      code: 403,
      msg: "拒绝访问API"
    }))
  }
  const { store_id } = ctx.query
  // let criteria = {}
  // if (store_id) {
  //   const storeIds = store_id.split(',')
  //   // criteria['store_id'] = {
  //   //   [Sequelize.Op.in]: storeIds
  //   // }
  // }
  const list = await StoreHouse.findAll({
    // where: criteria
  })
  ctx.body = new ResBody({ data: { list } })
})

// 添加门店；
router.post("/add", async ctx => {
  console.log('add--%s--%s==', JSON.stringify(ctx.request.body));
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return (ctx.body = new ResBody({
      success: false,
      code: 403,
      msg: "拒绝访问API"
    }))
  }
  const {
    id,
    store_no,
    store_name,
    store_type = 0,
    phone,
    area,
    area_address,
    config = "{}",
    is_show = 1
  } = ctx.request.body
  utils.checkParams({ store_no, store_name, area, area_address })
  let store;
  if (id) {
    store = await Store.update({
      store_name,
      store_type,
      phone,
      area,
      area_address,
      config,
      is_show
    },
      {
        where: {
          id
        }
      }
    )
  }
  else {
    store = await Store.findOrCreate({
      where: { [Op.or]: [{ id }, { store_no }, { store_name }] },
      defaults: {
        store_no,
        store_name,
        store_type,
        phone,
        area,
        area_address,
        config,
        is_show
      }
    })
  }
  console.log("findGoods--store:-%s==", JSON.stringify(store))
  if (id) {
    ctx.body = new ResBody({ data: store })
    return;
  }

  const store_id = store.length === 2 && store[1] ? store[0].id : ""
  // const store_house_name = `${store_name}-门店`
  const store_house_name = `门店`
  // const storeHouse = store.addStoreHouse({ store_id, store_house_name: '门店', area_address })
  const storeHouse =
    store_id &&
    (await StoreHouse.findOrCreate({
      where: { store_id, store_house_name },
      defaults: { store_id, store_house_name, area_address }
    }))

  console.log("findGoods--storeHouse:-%s==", JSON.stringify(storeHouse))

  // if (findGoods) {
  //   // throw new Error(`${goods_name}-${full_goods_name} 商品已存在`)
  //   return ctx.body = new ResBody({ success: false, msg: '该商品已存在' })
  // }
  // const goods = await Goods.createCate({ goods_name, full_goods_name, cat_id, attr, stock, sales, unit_name, unit_name2, unit_convert, unit_convert2, weight, desc, ord, store_id, is_hot, is_recommend, status, deleted, slider_image, content })
  ctx.body = new ResBody({ data: store })
})

// 添加仓库；
router.post("/addStoreHouse", async ctx => {
  console.log(
    "add--%s--%s==",
    JSON.stringify(ctx.request.body),
    JSON.stringify(ctx.state.user)
  )
  const { role } = ctx.state.user
  if (role !== "superAdmin") {
    // throw new Error("403-拒绝访问API")
    return (ctx.body = new ResBody({
      success: false,
      code: 403,
      msg: "拒绝访问API"
    }))
  }
  const { store_id, store_house_name, area_address } = ctx.request.body
  utils.checkParams({ store_id, store_house_name, area_address })

  const res = await StoreHouse.findOrCreate({
    where: { store_id, store_house_name },
    defaults: { store_id, store_house_name, area_address }
  })
  console.log("findGoods--%s==", res)
  // if (findGoods) {
  //   // throw new Error(`${goods_name}-${full_goods_name} 商品已存在`)
  //   return ctx.body = new ResBody({ success: false, msg: '该商品已存在' })
  // }
  // const goods = await Goods.createCate({ goods_name, full_goods_name, cat_id, attr, stock, sales, unit_name, unit_name2, unit_convert, unit_convert2, weight, desc, ord, store_id, is_hot, is_recommend, status, deleted, slider_image, content })
  ctx.body = new ResBody({ data: res })
})

module.exports = router.routes()
